<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/12
 * Time: 11:40
 */
namespace App\Repositories;

use App\Models\CardLogo;
use App\Models\RepaymentBill;
use App\Models\RepaymentPlan;
use App\Models\UserCreditCard;

class UserCreditCardRepository
{
    /**
     * 创建用户绑定的信用卡
     * @param array $params
     * @return mixed
     */
    public function create(array $params)
    {
        return UserCreditCard::create($params);
    }

    public function insertGetId($params)
    {
        return UserCreditCard::insertGetId($params);
    }

    /**
     * 根据id获取信用卡资料
     * @param $id
     * @return mixed
     */
    public function byId($id)
    {
        return UserCreditCard::find($id);
    }

    public function getCardToBind($userId)
    {
        return UserCreditCard::where([
            'user_id' => $userId,
            'is_bind' => 1,
        ])->orderby('id', 'desc')->get();
    }

    /**
     * 用户对应的信用卡是否存在
     * @param $id
     * @return mixed
     */
    public function validateCreditCardIsUser($id, $userId)
    {
        return UserCreditCard::where([
            'id' => $id,
            'user_id' => $userId,
        ])->first();
    }

    /**
     * 根据id获取用户绑定的信用卡资料
     * @param $id
     * @return mixed
     */
    public function ByUserId($id)
    {
        return UserCreditCard::where('user_id', $id)->first();
    }

    /**
     * 信用卡是否已经存在
     * @param $userId
     * @param $bankNo
     * @return mixed
     */
    public function isExistBankNo($bankNo)
    {
        return UserCreditCard::where('bank_no', $bankNo)->first();
    }

    /**
     * 用户是否已经存在信用卡
     * @param $userId
     * @param $bankNo
     * @return mixed
     */
    public function isExistUserBankNo($userId, $bankNo)
    {
        return UserCreditCard::where([
            'user_id' => $userId,
            'bank_no' => $bankNo
        ])->first();
    }

    public function getUserCreditCardListList($userId)
    {
        $creditCard = UserCreditCard::where([
            'user_id' => $userId,
            'is_bind' => 1,
        ])->orderby('id', 'desc')->get();
        $data = [];
        foreach ($creditCard as $key=>$value) {
            $cardLogo = CardLogo::where('bank_code', $value['bank_code'])->first();
            $data[$key] = $value;
            $billRepaymentDate = billRepaymentDate($value['bill_day'], $value['repayment_day']);
            //一个月有上个和这个还款日，两个的处理
            $monthBillDate = getMonthBillDate($value['bill_day'], $value['repayment_day']);
            $monthbill = RepaymentBill::where([
                'credit_card_id' => $value['id'],
                'user_id' => $value['user_id'],
                'month_bill_date' => $monthBillDate
            ])->first();
            //本期账单已还清则算当前日期是否小于账单日，小于待出账，多少天，大于的，判断本期本期金额
            //账单状态：0待出账 1待更新 2待还清 3已还清 4已逾期
            if (!empty($monthbill)) {
                $monthBillStatus = $monthbill->bill_status;
            } else {
                $monthBillStatus = billStatus($billRepaymentDate['bill_date'], $billRepaymentDate['repayment_date'], 0);
            }
            if (date('Ymd') < $billRepaymentDate['bill_date']) {
                //是本月还是下个月
                //本月账单逾期拿本月还款日
                if ($monthBillStatus != 3) {
                    //是否需要拿上个还款日
                    if ($value['bill_day'] > $value['repayment_day']) {
                        $diffDays = diffDate(date('Y-m-d'), $billRepaymentDate['repayment_last_date']);//距离还款多少天
                    } else {
                        $diffDays = diffDate(date('Y-m-d'), $billRepaymentDate['bill_date']);//距离账单日多少天
                    }
                } else {
                    //不逾期拿下个月账单日
                    $diffDays = diffDate(date('Y-m-d'), $billRepaymentDate['bill_next_date']);//距离账单日多少天
                }
                //没出账
                if ($value['bill_day'] > $value['repayment_day']) {
                    $diffNextDays = diffDate(date('Y-m-d'), $billRepaymentDate['bill_date']);//距离账单日多少天
                } else {
                    $diffNextDays = diffDate(date('Y-m-d'), $billRepaymentDate['bill_next_date']);//距离账单日多少天
                }
            } else {
                if ($monthBillStatus != 3) {
                    $diffDays = diffDate(date('Y-m-d'), $billRepaymentDate['repayment_date']);//距离还款多少天
                } else {
                    //已还清已出账
                    $diffDays = diffDate(date('Y-m-d'), $billRepaymentDate['repayment_date']);//距离还款多少天
                }
                $diffNextDays = diffDate(date('Y-m-d'), $billRepaymentDate['bill_next_date']);//距离账单日多少天
            }

            //是否拿下个月，取决于档期日期是否 到了 下个账单日
            if (date('Y-m') != $monthBillDate) {
                $billNextDate = $billRepaymentDate['bill_date'];//下个账单日
                $repaymentNextDate = $billRepaymentDate['repayment_date'];//下个还款日
            } else {
                $billNextDate = $billRepaymentDate['bill_next_date'];//下个账单日
                $repaymentNextDate = $billRepaymentDate['repayment_next_date'];//下个还款日
            }
            if (!empty($monthbill)) {
                $data[$key]['card_logo_url'] = !empty($cardLogo) ? getOssImageUrl($cardLogo->card_logo_url) : '';
                $data[$key]['repayment_bill_money'] = $monthbill->repayment_bill_money;

                $data[$key]['bill_id'] = $monthbill->id;
                $data[$key]['bill_date'] = $monthbill->bill_date;
                $data[$key]['repayment_date'] = $monthbill->repayment_date;
                $data[$key]['bill_next_date'] = strtotime($billNextDate);
                $data[$key]['repayment_next_date'] = strtotime($repaymentNextDate);

//                $data[$key]['bill_date'] = date('Y-m-d', $monthbill->bill_date);
//                $data[$key]['repayment_date'] = date('Y-m-d', $monthbill->repayment_date);
//                $data[$key]['bill_next_date'] = $billNextDate;
//                $data[$key]['repayment_next_date'] = $repaymentNextDate;

                $data[$key]['lowest_repayment_money'] = $monthbill->lowest_repayment_money;
                $data[$key]['bill_status'] = $monthbill->bill_status;
                $plan = RepaymentPlan::where([
                    'user_id' => $userId,
                    'repayment_bill_id' => $monthbill->id,
                ])->orderby('id', 'desc')->first();
                $data[$key]['plan_id'] = !empty($plan->id) ? $plan->id : 0;
                $data[$key]['plan_status'] = !empty($plan->repayment_plan_status) ? $plan->repayment_plan_status : 0;
                $data[$key]['diff_days'] = $diffDays;
                $data[$key]['bill_next_status'] = 0;
                $data[$key]['diff_next_days'] = $diffNextDays;
            } else {
                $data[$key]['card_logo_url'] = !empty($cardLogo) ? getOssImageUrl($cardLogo->card_logo_url) : '';
                $data[$key]['repayment_bill_money'] = '0.00';
                $data[$key]['bill_id'] = 0;
                $data[$key]['bill_date'] = strtotime($billRepaymentDate['bill_date']);
                $data[$key]['repayment_date'] = strtotime($billRepaymentDate['repayment_date']);
                $data[$key]['bill_next_date'] = strtotime($billNextDate);
                $data[$key]['repayment_next_date'] = strtotime($repaymentNextDate);
                $data[$key]['lowest_repayment_money'] = 0;
                $data[$key]['bill_status'] = $monthBillStatus;
                $data[$key]['plan_id'] = 0;
                $data[$key]['plan_status'] = 0;
                $data[$key]['diff_days'] = $diffDays;
                $data[$key]['bill_next_status'] = 0;
                $data[$key]['diff_next_days'] = $diffNextDays;
            }
        }
        return $data;
    }

    public function getCardList($request)
    {
        $page = $request->pageNumber - 1;
        $page = $page < 0 ? 0 : $page;
        $limit = $request->pageSize ? $request->pageSize : 50;
        $offset = $page * $limit;
        $query = UserCreditCard::from('user_credit_card as c')
            ->join('card_logo as l', 'c.bank_code', '=', 'l.bank_code')
            ->select('c.*', 'l.card_logo_url')
            ->where(function ($query) use ($request) {
                if (!is_null($request->is_bind)) {
                    $query->where('c.is_bind', $request->is_bind);
                }
                if (!empty($request->keyword)) {
                    switch ($request->field) {
                        case 'user_id':
                            $query->where('c.user_id', $request->keyword);
                            break;
                        case 'id':
                            $query->where('c.id', $request->keyword);
                            break;
                        case 'bank_code':
                            $query->where('c.bank_code', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'bank_no':
                            $query->where('c.bank_no', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'bank_description':
                            $query->where('c.bank_description', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'bank_mobile':
                            $query->where('c.bank_mobile', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'card_bin':
                            $query->where('c.card_bin', 'like', '%' . $request->keyword . '%');
                            break;
                        case 'bill_day':
                            $query->where('c.bill_day', $request->keyword);
                            break;
                        case 'repayment_day':
                            $query->where('c.repayment_day', $request->keyword);
                            break;
                    }
                }
                if (!empty($request->start_time) && !empty($request->end_time)) {
                    $query->whereBetween('c.create_time', [strtotime($request->start_time), strtotime($request->end_time)]);
                }
            });
        $total = $query->count();
        $result = $query->latest('c.id')
            ->offset($offset)
            ->limit($limit)
            ->get();
        return ['result' => $result, 'count' => $total];
    }
}